package com.tenbent.product.base.utils;

import java.lang.reflect.Method;

import com.tenbent.product.base.enums.base.BaseEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lihh
 * @since 2016/3/11 /2016-04-19 wei.zhao 整合enums工具类
 */
public class EnumUtil {

	private static final Logger logger = LoggerFactory.getLogger(EnumUtil.class);

	public static BaseEnum[] getEnums(Class<? extends BaseEnum> clazz) {
		try {
			Method valuesMethod = clazz.getMethod("values");
			Object obj = valuesMethod.invoke(clazz);
			BaseEnum[] enums = (BaseEnum[]) obj;
			return enums;
		} catch (Exception e) {
			logger.error("get enums error!");
			throw new RuntimeException(e);
		}
	}

	public static <T> T getByValue(Class<T> clazz, Integer value) {
		try {
			Method valuesMethod = clazz.getMethod("values");
			Object obj = valuesMethod.invoke(clazz);
			T[] enums = (T[]) obj;
			if (enums != null) {
				for (T anEnum : enums) {
					if (anEnum instanceof BaseEnum) {
						BaseEnum baseEnum = (BaseEnum) anEnum;
						if (value.equals(baseEnum.getValue())) {
							return anEnum;
						}
					}
				}
			}
			throw new RuntimeException("no value exists: " + value);
		} catch (Exception e) {
			logger.error("no value exists: " + value);
			throw new RuntimeException(e);
		}
	}

	public static <T extends Enum<?>> T get(String name, Class<T> clazz) {
		if (!clazz.isEnum()) {
			throw new IllegalArgumentException(clazz + "不是枚举类");
		} else {
			Enum[] values = clazz.getEnumConstants();
			Enum[] arr$ = values;
			int len$ = values.length;

			for (int i$ = 0; i$ < len$; ++i$) {
				Enum value = arr$[i$];
				if (StringUtils.equalsIgnoreCase(value.name(), name)) {
					return (T) value;
				}
			}

			return null;
		}
	}

	public static <T extends Enum<?>> T get(String name, Class<T> clazz, T defaultValue) {
		Enum value = get(name, clazz);
		return (T) (value == null ? defaultValue : value);
	}
}
